﻿using GalaSoft.MvvmLight.Threading;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using TYBase;
using TYControl;
using TYRTUBase;

namespace TYControl_For_RTU
{
    public partial class View_Config_Device_Switch : TYUserControl
    {
        private ViewModel_Config_Device_Switch vm = new ViewModel_Config_Device_Switch();
        private Device_Switch m_Switch;

        public View_Config_Device_Switch(Device_Switch _switch, System.Collections.ObjectModel.ObservableCollection<ViewModelComBase> listComInfo)
        {
            InitializeComponent();
            this.DataContext = vm;
            vm.ListComModel = listComInfo;
            SetIR(_switch);
        }

        private string section = "";


        private void SetIR(Device_Switch _switch)
        {
            m_Switch = _switch;
            if (m_Switch != null)
            {
                m_Switch.OnCom_Close_Connected += M_IR_OnCom_Close_Connected;

                m_Switch.OnComDataSend += M_Switch_OnComDataSend;
                m_Switch.OnComDataRead += M_Switch_OnComDataRead;
                section = m_Switch.EquipId;
                btnOpenCom.IsEnabled = true;
                btnOpenCom.Content = m_Switch.IsConnected ? "关闭" : "打开";
                vm.IsXMode = DataCenter.ini.ReadBoolEx(section, $"{EnumConfig_Device.IsXMode}", false);
                var com = DataCenter.ini.ReadIntEx(section, $"{EnumConfig_Device.Com}", 0);
                vm.SelectedCOM = vm.ListComModel.FirstOrDefault(x => x.Com == com);
                //这里读取配置
            }
        }

        private void M_IR_OnCom_Close_Connected(ITYClient sender, bool isConnected)
        {
            if (isConnected)
            {
                AddLog($"串口 {sender.ParaKey()}已打开!");
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    btnOpenCom.Content = "关闭";
                });
            }
            else
            {
                AddLog($"串口 {sender.ParaKey()}已关闭!");
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    btnOpenCom.Content = "打开";
                });
            }
        }

        private void M_Switch_OnComDataRead(ITYClient sender, byte[] data)
        {
            AddLog($"com:{sender.ParaKey()} 读到 hex:{data.AsHexString(' ')} data: {data.AsString()}");
        }

        private void M_Switch_OnComDataSend(ITYClient sender, byte[] data)
        {
            AddLog($"com:{sender.ParaKey()} 发送 hex:{data.AsHexString(' ')} data: {data.AsString()}");
        }

        private void AddLog(string message, bool showMBox = false)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
            {
                edit.AppendText($"{DateTime.Now.ToString("HH:mm:ss")} - {message}{Environment.NewLine}");
                if (showMBox)
                {
                    MessageBox.Show(message);
                    return;
                }
            });
        }

        private void BtnClick_Open_Close(object sender, RoutedEventArgs e)
        {
            if (m_Switch == null)
            {
                AddLog($"缓存串口为空!", true);
                return;
            }

            string btnContent = btnOpenCom.Content.ToString();
            if (btnContent == "打开")
            {
                if (vm.SelectedCOM == null)
                {
                    AddLog($"请选择串口", true);
                    return;
                }

                m_Switch.Close();
                m_Switch.Init(vm.SelectedCOM.Com);
                if (!m_Switch.Connect())
                {
                    AddLog($"打开{vm.SelectedCOM.Com}失败!", true);
                    return;
                }
                else
                {
                    AddLog($"打开{vm.SelectedCOM.Com}OK", true);
                    btnOpenCom.Content = "关闭";
                }
            }
            else
            {
                m_Switch.Close();
                btnOpenCom.Content = "关闭";
            }
        }

        private async void BtnClick_ReadIR(object sender, RoutedEventArgs e)
        {
            if (m_Switch == null)
            {
                AddLog($"缓存串口为空!", true);
                return;
            }
            if (vm.IsXMode)
            {
                AddLog($"模拟模式下直接返回OK! ", true);
                return;
            }
            AddLog($"开始读取");
            string data = "";
            int chan = vm.Chan;
            if (chan < 0)
            {
                AddLog($"通道号不能小于0");
            }
            var ret = await RunEx(() =>
            {
                return m_Switch.SwitchTo(chan);
            });
            if (ret)
            {
                AddLog($"切换 OK: {data} ");
            }
            else
            {
                AddLog($"切换: 失败!!!!! ", true);
            }
        }

        public async Task<bool> SaveIRPara()
        {
            if (vm.SelectedCOM == null)
            {
                AddLog($"请选择串口", true);
                return false;
            }
            bool isX = vm.IsXMode;
            if (m_Switch != null && section.NotNull())
            {
                DataCenter.ini.WriteBool(section, $"{EnumConfig_Device.IsXMode}", isX);
                DataCenter.ini.WriteInt(section, $"{EnumConfig_Device.Com}", vm.SelectedCOM.Com);

                string error = "";
                var ret = await RunEx(() =>
                  {
                      m_Switch.Close();
                      AddLog($"串口已关闭!", false);
                      return DataCenter.mDeviceHelper.Init(m_Switch, ref error);
                  });
                if (ret)
                {
                    AddLog($"打开串口成功");
                }
                else
                {
                    AddLog($"打开串口失败! {error}");
                }
                AddLog($"###############处理完成###############");
            }
            return true;
        }

        private async void BtnClick_Save(object sender, RoutedEventArgs e)
        {
            //if (!UserConfirmHelper.CheckUserLevel(EnumUserLevel.系统管理员 | EnumUserLevel.设备管理))
            //{
            //    return;
            //}
            await SaveIRPara();
        }

        private void BtnClick_ChangeSimulate(object sender, RoutedEventArgs e)
        {
            if (m_Switch == null)
            {
                AddLog("缓存 切换板为空!");
                return;
            }
            if (m_Switch != null)
            {
                m_Switch.SetIsXMode(vm.IsXMode);
                AddLog($"切换模拟 : {vm.IsXMode}");
            }
        }
    }
}